package org.lemon.transport.context.session;

import lombok.Getter;
import lombok.Setter;
import org.lemon.transport.context.data.device.Device;
import org.lemon.transport.context.data.device.DeviceProfile;
import org.lemon.transport.context.auth.TransportDeviceInfo;
import org.server.transport.gen.SessionProto;

import java.util.Optional;
import java.util.UUID;

public abstract class DeviceAwareSessionContext implements SessionContext {

    protected UUID sessionId;

    private volatile Long deviceId;
    @Getter
    protected volatile TransportDeviceInfo deviceInfo;
    @Getter
    @Setter
    protected volatile DeviceProfile deviceProfile;
    @Getter
    @Setter
    private volatile SessionProto.SessionInfoProto sessionInfo;

    @Setter
    private volatile boolean connected;

    public DeviceAwareSessionContext(UUID sessionId) {
        this.sessionId = sessionId;
    }

    public Long getDeviceId() {
        return deviceId;
    }

    public void setDeviceInfo(TransportDeviceInfo deviceInfo) {
        this.deviceInfo = deviceInfo;
        this.deviceId = deviceInfo.getDeviceId();
    }

    @Override
    public UUID getSessionId() {
        return null;
    }

    public boolean isConnected() {
        return connected;
    }

    public void setDisconnected() {
        this.connected = false;
    }

    @Override
    public void onDeviceProfileUpdate(SessionProto.SessionInfoProto sessionInfo, DeviceProfile deviceProfile) {
        this.sessionInfo = sessionInfo;
        this.deviceProfile = deviceProfile;
        this.deviceInfo.setDeviceType(deviceProfile.getName());
    }

    @Override
    public void onDeviceUpdate(SessionProto.SessionInfoProto sessionInfo, Device device, Optional<DeviceProfile> deviceProfileOpt) {

        this.sessionInfo = sessionInfo;
        this.deviceInfo.setDeviceProfileId(device.getDeviceProfileId());
        this.deviceInfo.setDeviceType(device.getType());
        deviceProfileOpt.ifPresent(profile -> this.deviceProfile = profile);
    }
}
